// 导入request模块
import request from './request'
import { isMockMode } from '../config';

// 创建医生信息
export const createDoctor = (hospital, department, position) => {
  return request.post('/users/doctor', {
    hospital,
    department,
    position
  })
}

// 获取自己的医生信息
export const getDoctorSelf = () => {
  return request.get('/users/doctor/self')
}

// 更新自己的医生信息
export const updateDoctorSelf = (data) => {
  return request.put('/users/doctor/self', data)
}

// 添加患者
export const addPatient = (userId, gender, age, idCard) => {
  return request.post('/users/patient', {
    user_id: userId,
    gender,
    age,
    id_card: idCard
  })
}

// 获取指定患者信息
export const getPatient = (patientUserId) => {
  return request.get(`/users/patient/${patientUserId}`)
}

// 获取用户信息
export const getUserInfo = (userId) => {
  return request.get(`/users/${userId}`)
}

// 创建评估记录
export const createAssessment = (userId, assessmentDate, hamdTotal, hamaTotal, ymrsTotal) => {
  return request.post('/assessments', {
    user_id: userId,
    assessment_date: assessmentDate,
    hamd_total: hamdTotal,
    hama_total: hamaTotal,
    ymrs_total: ymrsTotal
  })
}

// 提交HAMA量表详情（14题）
export const submitHama = (assessmentId, hamaData) => {
  return request.post(`/assessments/${assessmentId}/hama`, hamaData)
}

// 提交HAMD17抑郁量表详情（17题）
export const submitHamd17 = (assessmentId, hamd17Data) => {
  return request.post(`/assessments/${assessmentId}/hamd17`, hamd17Data)
}

// 提交YMRS狂躁量表详情（11题）
export const submitYmrs = (assessmentId, ymrsData) => {
  return request.post(`/assessments/${assessmentId}/ymrs`, ymrsData)
}

// 分页查看患者的所有评估记录
export const getPatientAssessments = (patientUserId, params = {}) => {
  // 支持两种调用方式：
  // 1. 旧方式：getPatientAssessments(patientUserId, page, size)
  // 2. 新方式：getPatientAssessments(patientUserId, { page, size, scale_type, time_range })
  
  let queryParams = {};
  
  if (typeof params === 'number') {
    // 旧方式：第二个参数是page
    const page = params;
    const size = arguments[2] || 10;
    queryParams = { page, size };
  } else if (typeof params === 'object') {
    // 新方式：第二个参数是对象
    queryParams = {
      page: params.page || 1,
      size: params.size || 10,
      scale_type: params.scale_type || 'all',
      time_range: params.time_range || 'all'
    };
  } else {
    // 默认参数
    queryParams = { page: 1, size: 10 };
  }
  
  return request.get(`/assessments/patient/${patientUserId}`, queryParams)
}

// 查看患者的某次评估详情
export const getPatientAssessmentDetails = (assessmentId) => {
  return request.get(`/assessments/${assessmentId}/details`)
}

// 搜索患者
export const searchPatients = (params) => {
  return request.get('/doctor/search-patients', params)
}

// 通过手机号搜索患者
export const searchPatientByPhone = (phone) => {
  console.log('[API] 通过手机号搜索患者:', phone);
  return request.get('/doctor/search-patients', {
    phone
  })
}

// 通过姓名搜索患者
export const searchPatientByName = (name) => {
  console.log('[API] 通过姓名搜索患者:', name);
  return request.get('/doctor/search-patients', {
    name
  })
}

// 绑定患者到当前医生
export const bindPatientToDoctor = (patientUserId) => {
  console.log('[API] 绑定患者:', patientUserId);
  return request.post('/doctor/bind-patient', {
    patient_id: patientUserId  // 后端期望的参数名是 patient_id
  })
}

// 解除患者绑定
export const unbindPatientFromDoctor = (patientUserId) => {
  console.log('[API] 解除绑定患者:', patientUserId);
  return request.post('/doctor/unbind-patient', {
    patient_id: patientUserId  // 后端期望的参数名是 patient_id
  })
}

// 绑定患者（旧方法，保持兼容性）
export const bindPatient = (patientId) => {
  return request.post('/doctor/bind-patient', {
    patient_id: patientId
  })
}

// 获取已绑定患者列表
export const getBoundPatients = () => {
  return request.get('/doctor/bound-patients')
}

// 解绑患者（旧方法，保持兼容性）
export const unbindPatient = (patientId) => {
  return request.post('/doctor/unbind-patient', {
    patient_id: patientId
  })
}

// 为患者建档（医生代建）- 旧方法，仅为已有user创建详细信息
export const createPatientProfile = (patientData) => {
  return request.post('/users/patient', patientData)
}

// 医生创建患者完整账号（新增）- 包含user + user_patient + 自动绑定
export const createPatientAccount = (patientData) => {
  console.log('[API] 医生创建患者完整账号:', patientData);
  return request.post('/doctor/create-patient-account', {
    phone: patientData.phone,
    real_name: patientData.real_name,
    gender: patientData.gender,
    age: patientData.age,
    id_card: patientData.id_card
  })
}

/**
 * 医生登录
 * @param {Object} params - 登录参数
 * @param {Object} params.user_info - 用户信息对象
 * @returns {Promise<Object>} 登录结果
 */
export default async function doctorLogin(params = {}) {
  try {
    // 提取用户信息
    const { user_info = {} } = params;
    
    // 验证必填字段
    if (!user_info.name || !user_info.phone || !user_info.hospital || !user_info.department || !user_info.position) {
      throw new Error('医生登录信息不完整：姓名、手机号、医院、科室和职位为必填项');
    }
    
    // 构造请求数据
    const requestData = {
      user_info: {
        name: user_info.name,
        phone: user_info.phone,
        hospital: user_info.hospital,
        department: user_info.department,
        position: user_info.position,
        age: user_info.age,
        gender: user_info.gender || 'male'
      }
    };
    
    console.log('医生登录请求数据:', requestData);
    
    if (isMockMode) {
      // 模拟登录响应
      return {
        data: {
          token: 'mock_doctor_token_' + Date.now(),
          user_info: {
            id: '2',
            name: user_info.name,
            phone: user_info.phone,
            hospital: user_info.hospital,
            department: user_info.department,
            position: user_info.position,
            age: user_info.age,
            gender: user_info.gender || 'male',
            user_type: 'doctor',
            role: 'doctor'
          }
        }
      };
    }
    
    // 调用实际登录接口
    const response = await request.post('/auth/doctor/login', requestData);
    return response;
  } catch (error) {
    console.error('医生登录失败:', error);
    throw error;
  }
}

/**
 * 导出单次评估PDF（包含完整量表）
 * @param {Number} assessmentId - 评估ID
 * @returns {Promise<String>} 返回临时文件路径
 */
export const exportAssessmentPDF = (assessmentId) => {
  console.log('[API] 导出评估PDF:', assessmentId);
  return request.download(`/doctor/export-assessment-pdf/${assessmentId}`)
}